package com.maltys.tree;

import com.maltys.tree.base.TreeNode;

/**
 * @author Maltyts
 * @link <a href="https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/">...</a>
 */
public class ConstructBinaryTree1 {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return build(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
    }

    private TreeNode build(int[] inorder, int[] postorder, int inStart, int inEnd, int postStart, int postEnd) {
        if (inorder.length == 0 || inStart > inEnd) {
            return null;
        }
        if (inStart == inEnd) {
            return new TreeNode(inorder[inStart]);
        }
        int rootVal = postorder[postEnd];
        TreeNode root = new TreeNode(rootVal);
        int rootIdx = -1;
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == rootVal) {
                rootIdx = i;
                break;
            }
        }
        root.left = build(inorder, postorder, inStart, rootIdx - 1, postStart, postStart + rootIdx - inStart - 1);
        root.right = build(inorder, postorder, rootIdx + 1, inEnd, postStart + rootIdx - inStart, postEnd - 1);
        return root;
    }

    public static void main(String[] args) {
        ConstructBinaryTree1 con = new ConstructBinaryTree1();
        TreeNode treeNode = con.buildTree(new int[]{2, 1}, new int[]{1, 2});
        System.out.println(treeNode.val);
    }
}
